#include "driver/spi_master.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <stdio.h>
#include <string.h>

void app_main(void)
{
	esp_err_t ret;
	spi_device_handle_t spi;
	spi_transaction_t t;
	uint8_t data = 0x7A;

	spi_bus_config_t buscfg = {
		.miso_io_num = 2,
		.mosi_io_num = 7,
		.sclk_io_num = 6,
		.quadwp_io_num = -1,
		.quadhd_io_num = -1,
		.max_transfer_sz = 16,
	};

	spi_device_interface_config_t devcfg = {
		.clock_speed_hz = 2400000, // Clock out at 2.4 MHz
		.mode = 0,                 // SPI mode 0
		.spics_io_num = 10,        // CS pin
		.queue_size = 7,           // We want to be able to queue 7 transactions at a time
	};

	ret = spi_bus_initialize(SPI2_HOST, &buscfg, SPI_DMA_CH_AUTO);
	ESP_ERROR_CHECK(ret);

	ret = spi_bus_add_device(SPI2_HOST, &devcfg, &spi);
	ESP_ERROR_CHECK(ret);

	memset(&t, 0, sizeof(t)); // Zero out the transaction
	t.length = 8;             // Command is 8 bits
	t.tx_buffer = &data;      // The data is the cmd itself

	while (1) {
		ret = spi_device_polling_transmit(spi, &t); // Transmit!
		ESP_ERROR_CHECK(ret);

		vTaskDelay(200 / portTICK_PERIOD_MS);
	}
}
